package cn.itheima.server_request;

import cn.itheima.bean.Student;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

//2.使用POST提交获取请求参数，使用工具类封装为javabean对象，二个获取请求参数的方法（获取一个，一个数组）
@WebServlet("/ServletTest2")
public class ServletTest2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //设置编码类型 防止中文乱码
        request.setCharacterEncoding("UTF-8");
        Map<String, String[]> parameterMap = request.getParameterMap();

        //封装为Javabean对象
        Student stu = new Student();
        try {
            BeanUtils.populate(stu, parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //获取请求参数(单个)
        System.out.println(request.getParameter("username"));;
        System.out.println(request.getParameter("password"));;
        //获取多个
        String[] hobbies = request.getParameterValues("hobby");
        System.out.println(Arrays.toString(hobbies));

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
